package com.maddox.relax.nfc

import android.app.PendingIntent
import android.content.Intent
import android.nfc.NdefMessage
import android.nfc.NdefRecord
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.maddox.relax.R
import com.maddox.relax.databinding.ActivityNfcReadBinding
import com.maddox.relax.util.AppUtils
import com.maddox.relax.util.LogUtil
import java.nio.charset.Charset
import java.util.*

/**
 * Nfc读取页面
 */
class NfcReadActivity : AppCompatActivity() {

    lateinit var nfcAdapter: NfcAdapter
    lateinit var pendingIntent: PendingIntent
    lateinit var bd:ActivityNfcReadBinding

    //是否启用加密校验
    var isEncrypt = false


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bd =DataBindingUtil.setContentView(this,R.layout.activity_nfc_read)
        initView()
    }

    private fun initView() {
        bd.header.toolbarTitle.text = "读取信息"
        nfcAdapter = NfcAdapter.getDefaultAdapter(this)
        if (nfcAdapter == null) {
            Toast.makeText(this, "当前设备不支持NFC", Toast.LENGTH_SHORT).show()
            return
        }
        pendingIntent = PendingIntent.getActivity(this, 0, Intent(this, this::class.java), 0)
        bd.toggleDecrypt.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) isEncrypt =true else isEncrypt=false
        }
    }

    override fun onResume() {
        super.onResume()
        nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null)
    }

    override fun onPause() {
        super.onPause()
        nfcAdapter.disableForegroundDispatch(this)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        val tag: Tag? = intent?.getParcelableExtra(NfcAdapter.EXTRA_TAG)
        if (tag == null) return
        //tag.techList.contains("android.nfc.tech.Ndef")
        if (NfcAdapter.ACTION_NDEF_DISCOVERED == intent.action) {
            val sbf = StringBuilder()
            try {
                intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES).also { rawMessages ->
                    val messages = rawMessages.map { it as NdefMessage }
                    messages.forEach { ndefMessage ->
                        val byteArrayLength = ndefMessage.byteArrayLength
                        ndefMessage.records.forEach { ndefRecord ->
                            val parseResult = parseText(tag, ndefRecord)
                            sbf.append(parseResult)
                        }
                    }

                }
            } catch (e: Exception) {
                e.printStackTrace()
                LogUtil.d("解析Nfc异常:${e.message}")
            }
            //显示读取到的信息
            bd.nfcInfo.text = sbf.toString()
        }

    }

    private fun parseText(tag: Tag, ndefRecord: NdefRecord): String {
        //验证过滤非文本内容类型
        if (ndefRecord.tnf != NdefRecord.TNF_WELL_KNOWN) return ""
        if (!Arrays.equals(ndefRecord.type, NdefRecord.RTD_TEXT)) return ""

        val payload = ndefRecord.payload
        val textEncoding = if ((payload[0].toInt() and 0x80) == 0) "UTF-8" else "UTF-16"
        val languageCodeLength = payload[0].toInt() and 0x3f
        var rtext = String(
            payload,
            1 + languageCodeLength,
            payload.size - languageCodeLength - 1,
            Charset.forName(textEncoding)
        )
        if (isEncrypt) {
            rtext = AppUtils.aesDecrypt(rtext, AppUtils.byteArrayToHexString(tag.id))
        }
        return rtext
    }


}